package org.lionel;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class DownloadFile {
    public static void main(String[] args) throws IOException {
        for (int i = 1;i<=102;i++)
        download(i);
    }

    private static void download(int i) throws IOException {
        // 图片路径
        String url = "https://public.vzkoo.com/report-image/2021/1217/ab9b568070edf9674d34c3968d2ab8f6/"+i+".jpg?x-oss-process=image/resize,w_1586,m_lfit";
        // 创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httpGet实例
        HttpGet httpGet = new HttpGet(url);
        // 设置请求头消息
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 获取 .后缀
        String fileName = url.substring(url.lastIndexOf("."));

        if(response != null){
            HttpEntity entity = response.getEntity();  // 获取返回实体
            EntityUtils.toString(response.getEntity());
            if(entity != null){
                System.out.println("Content-Type:" + entity.getContentType().getValue());
                InputStream inputStream =  entity.getContent();
                // 文件复制，common io 包下，需要 引入依赖
                FileUtils.copyToFile(inputStream, new File("D:\\resources\\"+i+".jpg"));
            }
        }
        if(response != null){
            response.close();
        }
        if(httpClient != null){
            httpClient.close();
        }
    }


}
